package org.gas;

/*
 * 获取Docker官方仓库crt证书
 * Jdk 17
 * Kotlin 1.8.20
 * Scala 3.2.2
 * By gas
 * */

import java.net.URL;
import java.util.Base64;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateEncodingException;


public class Application {
    private static final String host = "index.docker.io";
    private static final String crtPath = String.format("/etc/ssl/certs/%s.crt", host);
    private static final BufferedWriter crtFile;
    static {
        try {
            crtFile = new BufferedWriter(new FileWriter(crtPath, true));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        // 连接网站
        URL url = new URL(String.format("https://%s:443", host));
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        // 获取证书
        Certificate[] crt = conn.getServerCertificates();
        // 保存证书
        String cPem = "";
        for (Certificate i : crt) {
            cPem = crtPEMFormat((X509Certificate) i);
            crtFile.write(cPem);
        }
        crtFile.close();
    }

    // 将证书转换为 PEM 格式
    public static String crtPEMFormat(X509Certificate crt) throws CertificateEncodingException {
        return "-----BEGIN CERTIFICATE-----\n" +
                Base64.getEncoder().encodeToString(crt.getEncoded()) +
                "\n-----END CERTIFICATE-----\n";
    }

    // JDK15及以上写法
    /*public static String crtPEMFormat(X509Certificate crt) throws CertificateEncodingException {
        String crtPem = """
                -----BEGIN CERTIFICATE-----
                %s
                -----END CERTIFICATE-----
                """;
        return crtPem.formatted(Base64.getEncoder().encodeToString(crt.getEncoded()));
    }*/
}